<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="登录名" prop="loginName">
        <el-input v-model="formData.loginName" disabled />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <InputPassword v-model="formData.newPassword" strength />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <InputPassword v-model="formData.confirmPassword" strength />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { InputPassword } from '@/components/InputPassword'
import { resetPassword } from '@/api/system/user'

defineOptions({ name: 'ResetPasswordForm' })

const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('重置密码') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：提交表单时，禁用表单操作
const formRef = ref<FormInstance>() // 表单 Ref

// 表单校验
const equalToPassword = (_rule, value, callback) => {
  if (formData.newPassword !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}
let userUid: string | undefined
const formData = reactive({
  loginName: '',
  newPassword: '',
  confirmPassword: ''
})

const formRules = reactive<FormRules>({
  newPassword: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})

/** 打开弹窗 */
const open = async (uid: string, loginName: string) => {
  dialogVisible.value = true
  resetForm()
  // 设置数据
  userUid = uid
  formData.loginName = loginName
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // TODO: 调用重置密码的 API
    const resetParams = {
      uid: userUid!,
      password: formData.newPassword,
      confirmPassword: formData.confirmPassword
    }
    resetPassword(resetParams)
    message.success('重置成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  userUid = undefined
  formData.newPassword = ''
  formData.confirmPassword = ''
  formRef.value?.resetFields()
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>
